package com.hong610.quartz.extend;

import com.hong610.quartz.core.QuartzManager;
import com.hong610.quartz.entity.JobClassInfo;
import com.hong610.utils.ClassPackageScanner;
import com.hong610.utils.PackageScanner;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.quartz.impl.triggers.CronTriggerImpl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 调度任务帮助类
 * Created by Hong on 2017/2/8.
 */
public class QuartzJob {

    private static QuartzManager quartzManager = new QuartzManager();

    /**
     * 获取工作任务Class类
     * @param triggerName 触发器
     * @param groupName 工作组
     */
    public static String getJobClass(String triggerName, String groupName){
        CronTriggerImpl cronTrigger = quartzManager.getCronTrigger(triggerName, groupName);
        if(cronTrigger == null)
            return null;
        try {
            JobDetail jobDetail = quartzManager.getScheduler().getJobDetail(cronTrigger.getJobKey());
            return jobDetail.getJobClass().getName();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取Cron表达式
     * @param triggerName 触发器
     * @param groupName 工作组
     */
    public static String getCronExpression(String triggerName, String groupName){
        CronTriggerImpl cronTrigger = quartzManager.getCronTrigger(triggerName, groupName);
        if(cronTrigger == null)
            return null;
        return cronTrigger.getCronExpression();
    }

    /**
     * 获取项目中全部的工作任务类
     * @return
     * @throws IOException
     */
    public static List<JobClassInfo> getQuartzJobClass() throws IOException {
        PackageScanner scanner = new ClassPackageScanner("com.hong610.quartz.job");
        List<JobClassInfo> list = new ArrayList();
        for(String path : scanner.getFullyQualifiedClassNameList(false)){
            JobClassInfo jobClassInfo = getQuartzJobInfo(path);
            if(jobClassInfo != null)
                list.add(jobClassInfo);
        }
        return list;
    }

    /**
     * 判断类是否是调度任务
     * @param classPath class包路径
     * @return
     */
    private static JobClassInfo getQuartzJobInfo(String classPath){
        try {
            Class cls = Class.forName(classPath);
            com.hong610.quartz.annotation.QuartzJob job = (com.hong610.quartz.annotation.QuartzJob)cls.getAnnotation(com.hong610.quartz.annotation.QuartzJob.class);
            if(job == null || job.skip())
                return null;
            return new JobClassInfo(classPath, job.text());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
